package com.soulgame.sms;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.text.TextUtils;

import com.android.volley.VolleyError;
import com.soul.record.RecordAgent;
import com.soul.sdk.SGProxy;
import com.soul.sdk.common.ActivityListenerAdapter;
import com.soul.sdk.constants.ResultCode;
import com.soul.sdk.plugin.pay.IPayCallBack;
import com.soul.sdk.plugin.pay.PayParams;
import com.soul.sdk.plugin.user.IExitListener;
import com.soul.sdk.utils.SGDebug;
import com.soul.sdk.utils.ToastUtil;
import com.soul.sdk.utils.json.KJSONObject;
import com.soulgame.sgsdkproject.sgtool.AmountUtils;
import com.soulgame.sgsdkproject.sgtool.DeviceUtil;
import com.soulgame.sgsdkproject.sgtool.SGLog;
import com.soulgame.sgsdkproject.sgtool.net.IStringHttpListener;
import com.soulgame.sgsdkproject.sgtool.net.VolleyRequest;
import com.soulgame.sms.common.PayTypeConfig;
import com.soulgame.sms.contant.PayType;
import com.soulgame.sms.net.NetUtils;
import com.soulgame.sms.pay.ADMPay;
import com.soulgame.sms.pay.EGamePay;
import com.soulgame.sms.pay.MMPay;
import com.soulgame.sms.pay.MiGuPay;
import com.soulgame.sms.pay.SMSPay;
import com.soulgame.sms.pay.WoShopPay;
import com.soulgame.sms.pay.vo.VoADMPayParams;
import com.soulgame.sms.pay.vo.VoPayParams;
import com.soulgame.sms.pay.vo.VoWoShopPayParams;

/**
 * @author lch
 * @version Create time：2017-3-14
 * @类说明：各种短代支付统一入口类
 */
public class SMSSdk extends ActivityListenerAdapter {

	private static SMSSdk mSmsSdk = null;

	private Activity mActivity;

	/**
	 * 各种支付入口类 集合，咪咕、MM、联通、爱游戏、爱动漫。。。
	 */
	private Map<String, SMSPay> mSMSPayMap = null;

	private SMSSdk() {
		this.mSMSPayMap = new HashMap<String, SMSPay>(3);
	}

	public static SMSSdk getInstance() {

		if (mSmsSdk == null) {
			synchronized (SMSSdk.class) {
				mSmsSdk = new SMSSdk();
			}
		}
		return mSmsSdk;
	}

	/**
	 * 初始化
	 * 
	 * @param pActivity
	 * @param kjsonObject
	 */
	public void init(Activity pActivity, KJSONObject pSdkParamsJSON) {
		this.mActivity = pActivity;
		this.addSMSPay();
		// 为此类(继承于 ActivityListenerAdapter) 添加 Activity 生命周期驱动监听
		SGProxy.getInstance().registerActivityListener(this);
		//
		for (SMSPay mSMSPay : this.mSMSPayMap.values()) {
			// 初始化
			mSMSPay.init(pActivity, pSdkParamsJSON);
		}
	}

	// =======================================================
	// 支付相关
	// =======================================================
	/**
	 * 支付入口
	 * 
	 * @param pActivity
	 * @param pPayParams
	 * @param pPayCallBack
	 */
	public void pay(final Activity pActivity, final PayParams pPayParams, final IPayCallBack pPayCallBack) {

		if (pPayParams == null || pPayCallBack == null) {
			ToastUtil.showShort(pActivity, "PayParams & IPayCallBack 均不能为 null");
			return;
		}
		// 获取当前支付的类型 根据实际情况判定使用哪种支付
		SMSPay mSMSPay = getSMSPay(PayTypeConfig.getInstance(pActivity).getPayType());
		if (mSMSPay == null) {
			// 不存在正常支付类型时，尝试获取默认支付
			mSMSPay = getSMSPay(PayTypeConfig.getInstance(pActivity).getDefaultPayType());
		}

		final SMSPay aSmsPay = mSMSPay;
		if (aSmsPay != null) {
			SGProxy.getInstance().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					doPay(pActivity, aSmsPay, pPayParams, pPayCallBack);
				}
			});

		} else {
			// TODO 没有合适的SMS支付通道，可以考虑回调给渠道支付
			SGDebug.print_w(this, "没有合适的SMS支付通道");
			// 支付失败回调
			if (pPayCallBack != null) {
				pPayCallBack.onFail(ResultCode.CODE_PAY_NOSMS_PAYTYPE, ResultCode.getMessage(ResultCode.CODE_PAY_NOSMS_PAYTYPE), pPayParams);
			}
		}

	}

	/**
	 * 找到了合适的短代支付通道，开始支付
	 * 
	 * @param pActivity
	 * @param pSmsPay
	 * @param pPayParams
	 * @param pPayCallBack
	 */
	private void doPay(final Activity pActivity, final SMSPay pSmsPay, final PayParams pPayParams,
			final IPayCallBack pPayCallBack) {

		String sdkOrderId = "";
		String urlPayType = "";
		//
		String auit = RecordAgent.getAuit(pActivity);
		String phoneToken = DeviceUtil.getPhoneToken(pActivity);
		String appToken = DeviceUtil.getAppToken(pActivity);

		String payType = pSmsPay.getPayType();

		VoPayParams voPayParams = pSmsPay.getVoPayParams();

		String productId = pPayParams.getProductId();

		String price = pPayParams.getPrice();

		KJSONObject extrainfo = KJSONObject.createJsonObject();

		if (PayType.MIGU.equals(payType)) {
			// 咪咕 咪咕规定长度为 16
			sdkOrderId = NetUtils.getOrderId(phoneToken, 16);
			urlPayType = NetUtils.PAY_TYPE_MIGU;

		} else if (PayType.MM.equals(payType)) {
			// MM 弱联网不超过16位，强联网不超过64位
			sdkOrderId = NetUtils.getOrderId(phoneToken, 16);
			urlPayType = NetUtils.PAY_TYPE_MM;

		} else if (PayType.WOSHOP.equals(payType)) {
			// 沃商店 联通订单必须为24位
			sdkOrderId = NetUtils.getOrderId(phoneToken, 24);
			urlPayType = NetUtils.PAY_TYPE_WOSHOP;
			//
			if (voPayParams != null && voPayParams instanceof VoWoShopPayParams) {
				VoWoShopPayParams voWoShopPayParams = (VoWoShopPayParams) voPayParams;
				String serviceId = voWoShopPayParams.getServiceId(productId);
				//
				SGDebug.d(this, "serviceId = " + serviceId);
				//
				extrainfo.put("serviceid", serviceId);
				extrainfo.put("ip_address", DeviceUtil.getLocalIpAddress(pActivity));
				extrainfo.put("mac_address", DeviceUtil.getLocalMacAddress(pActivity));
			}

		} else if (PayType.EGAME.equals(payType)) {
			// 爱游戏
			sdkOrderId = NetUtils.getOrderId(phoneToken, 16);
			urlPayType = NetUtils.PAY_TYPE_EGAME;

		} else if (PayType.ADM.equals(payType)) {
			
			if(voPayParams != null && voPayParams instanceof VoADMPayParams){
				//爱动漫最大的价格是 20; 由于爱动漫的计费金额与其他运营商的不一致，此处不使用游戏传参
				VoADMPayParams voADMPayParams = (VoADMPayParams) voPayParams;
				String aPrice = voADMPayParams.getPayPrice(productId);
				price = AmountUtils.changeY2F(aPrice);
			}
			
			// 爱动漫 商量好订单号 16位
			sdkOrderId = NetUtils.getOrderId(phoneToken, 16);
			urlPayType = NetUtils.PAY_TYPE_ADM;
		}

		//
		String sign = NetUtils.getSign(appToken, phoneToken, sdkOrderId, price + "", NetUtils.SIGN_KEY);

		String appOrderId = pPayParams.getAppOrderId();
		//
		final Map<String, String> mPayParmsMap = new HashMap<String, String>();
		mPayParmsMap.put(NetUtils.PARAM_AUIT, auit);
		mPayParmsMap.put(NetUtils.PARAM_APP_TOKEN, appToken);
		mPayParmsMap.put(NetUtils.PARAM_PHONE_TOKEN, phoneToken);
		mPayParmsMap.put(NetUtils.PARAM_ORDERID, sdkOrderId);
		mPayParmsMap.put(NetUtils.PARAM_GOODSID, productId);
		mPayParmsMap.put(NetUtils.PARAM_GAME_ORDER, appOrderId);
		mPayParmsMap.put(NetUtils.PARAM_PRICE, price + "");
		mPayParmsMap.put(NetUtils.PARAM_SIGN, sign);
		//
		mPayParmsMap.put(NetUtils.PARAM_EXTRAINFO, extrainfo.toString());

		// 发送状态，0未发送短信，1发送成功，2发送失败，3取消发送
		mPayParmsMap.put(NetUtils.PARAM_STATUS, "0");
		//
		// 设置本SDK生成的订单号
		pPayParams.setSdkOrderId(sdkOrderId);
		// 设置支付类型
		pPayParams.setPayType(pSmsPay.getPayType());
		
		String urlNickname = voPayParams.getUrlNickname();
		//
		SGDebug.d(this, "urlNickname = " + urlNickname);
		//  通知 Url 
		final String payEventUrl = NetUtils.getOrderUrl(urlNickname, urlPayType);

		// 网游还是单机
		final boolean isOnlineGame = SGProxy.getInstance().isOnlineGame();

		VolleyRequest.sendPostStringRequest(pActivity, payEventUrl, mPayParmsMap, new IStringHttpListener() {

			@Override
			public void onResponse(String response) {

				if (response != null) {
					SGLog.i("response:" + response);

					try {
						JSONObject responseJSON = new JSONObject(response);
						int code = responseJSON.optInt("code");
						String msg = responseJSON.optString("msg");
						SGLog.i("response msg:" + msg);
						if (code == 2000) {
							// 下单成功
							if (isOnlineGame) {
								// 网游是服务端发道具，需等下单成功后调起支付，单机的不用等
								pSmsPay.pay(pActivity, pPayParams,
										getSMSPayCallBack(pActivity, payEventUrl, mPayParmsMap, pPayCallBack));
							}
						} else {
							// 下单失败
							if (isOnlineGame) {
								pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "下单失败 code ！= 2000", pPayParams);
							}
						}

					} catch (Exception e) {
						// 下单异常
						if (isOnlineGame) {
							pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "下单出现了异常", pPayParams);
						}
						SGLog.e(e.toString());
					}

				} else {
					// 下单失败
					if (isOnlineGame) {
						pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "下单失败，服务端返回 response 为null", pPayParams);
					}
				}

			}

			@Override
			public void onErrorResponse(VolleyError error) {
				// 下单失败
				if (isOnlineGame) {
					pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "下单失败VolleyError", pPayParams);
				}
				if (error != null) {
					SGLog.i("onErrorResponse:" + error.toString());
				}
			}
		});

		if (!isOnlineGame) {
			// 网游等待下单成功后
			// 单机不用等待下单成功后
			pSmsPay.pay(pActivity, pPayParams, getSMSPayCallBack(pActivity, payEventUrl, mPayParmsMap, pPayCallBack));
		}

	}

	/**
	 * @param pPayCallBack
	 * @return 支付回调实例，这里中转一次是为了作统一 的 支付前后 往自家服务器上传统计数据
	 */
	private IPayCallBack getSMSPayCallBack(final Activity pActivity, final String payEventUrl,
			final Map<String, String> pPayParmsMap, final IPayCallBack pPayCallBack) {
		return new IPayCallBack() {

			@Override
			public void onSuccess(int resultCode, String sucessInfo, PayParams pPayParams) {

				if (pPayCallBack != null) {
					pPayCallBack.onSuccess(resultCode, sucessInfo, pPayParams);
				}

				// 发送状态，0未发送短信，1发送成功，2发送失败，3取消发送
				pPayParmsMap.put(NetUtils.PARAM_STATUS, "1");
				VolleyRequest.sendPostStringRequest(pActivity, payEventUrl, pPayParmsMap, new IStringHttpListener() {

					@Override
					public void onResponse(String response) {

					}

					@Override
					public void onErrorResponse(VolleyError error) {

					}
				});

			}

			@Override
			public void onFail(int errorCode, String failInfo, PayParams pPayParams) {

				if (pPayCallBack != null) {
					pPayCallBack.onFail(errorCode, failInfo, pPayParams);
				}

				if (ResultCode.CODE_PAY_CANCEL == errorCode) {
					// 发送状态，0未发送短信，1发送成功，2发送失败，3取消发送
					pPayParmsMap.put(NetUtils.PARAM_STATUS, "3");
				} else {
					// 发送状态，0未发送短信，1发送成功，2发送失败，3取消发送
					pPayParmsMap.put(NetUtils.PARAM_STATUS, "2");
				}

				VolleyRequest.sendPostStringRequest(pActivity, payEventUrl, pPayParmsMap, new IStringHttpListener() {

					@Override
					public void onResponse(String response) {

					}

					@Override
					public void onErrorResponse(VolleyError error) {

					}
				});

			}
		};

	}

	// =======================================================
	//
	// =======================================================
	/**
	 * 退出的时候调用
	 * 
	 * @param pActivity
	 * @param customParams
	 * @param pExitListener
	 */
	public void exit(Activity pActivity, Map<String, String> customParams, IExitListener pExitListener) {

		if (mSMSPayMap != null) {
			final SMSPay mMiguSMSPay = getSMSPay(PayType.MIGU);
			final SMSPay mEGameSMSPay = getSMSPay(PayType.EGAME);
			if (mMiguSMSPay != null) {
				// 咪咕的有退出弹框（新版SDK非官方包可以调无退出弹框UI的退出接口）,可以根据渠道号判断来选择处理。
				mMiguSMSPay.exit(pActivity, customParams, pExitListener);
			} else if (mEGameSMSPay != null) {
				// 爱游戏的短代SDK,官方包要求有退出弹框---官方包时不会有咪咕SDK
				mEGameSMSPay.exit(pActivity, customParams, pExitListener);
			} else {
				if (pExitListener != null) {
					pExitListener.onExit(customParams);
				}
			}

		} else {
			if (pExitListener != null) {
				pExitListener.onExit(customParams);
			}
		}

	}

	/**
	 * 更多游戏入口，目前 是 爱游戏官方包有这个需求
	 * 
	 * @param pContext
	 */
	public void moreGame(Activity pActivity) {
		for (SMSPay mSMSPay : this.mSMSPayMap.values()) {
			mSMSPay.moreGame(pActivity);
		}
	}

	// =======================================================
	//
	// =======================================================
	/**
	 * 添加支付方式：咪咕、MM、联通、爱游戏、爱动漫。。。 考虑根据 配置 及手机卡本身情况 确定会用到那种方式
	 */
	private void addSMSPay() {
		// 咪咕
		if (PayTypeConfig.getInstance(mActivity).isSupportPayType(PayType.MIGU)) {
			this.putSMSPay(PayType.MIGU);
		}
		// MM
		if (PayTypeConfig.getInstance(mActivity).isSupportPayType(PayType.MM)) {
			this.putSMSPay(PayType.MM);
		}
		// 联通
		if (PayTypeConfig.getInstance(mActivity).isSupportPayType(PayType.WOSHOP)) {
			this.putSMSPay(PayType.WOSHOP);
		}
		// 爱游戏
		if (PayTypeConfig.getInstance(mActivity).isSupportPayType(PayType.EGAME)) {
			this.putSMSPay(PayType.EGAME);
		}
		// 爱动漫
		if (PayTypeConfig.getInstance(mActivity).isSupportPayType(PayType.ADM)) {
			this.putSMSPay(PayType.ADM);
		}

		if (this.mSMSPayMap.isEmpty()) {
			// 如果没有正常判断合适的情况，使用配置默认的
			String defaultPayType = PayTypeConfig.getInstance(mActivity).getDefaultPayType();
			if (!TextUtils.isEmpty(defaultPayType)) {
				this.putSMSPay(defaultPayType);
			}
		}
	}

	private void putSMSPay(String pPayType) {
		if (PayType.MIGU.equals(pPayType)) {
			this.mSMSPayMap.put(PayType.MIGU, new MiGuPay());
		} else if (PayType.MM.equals(pPayType)) {
			this.mSMSPayMap.put(PayType.MM, new MMPay());
		} else if (PayType.WOSHOP.equals(pPayType)) {
			this.mSMSPayMap.put(PayType.WOSHOP, new WoShopPay());
		} else if (PayType.EGAME.equals(pPayType)) {
			this.mSMSPayMap.put(PayType.EGAME, new EGamePay());
		} else if (PayType.ADM.equals(pPayType)) {
			this.mSMSPayMap.put(PayType.ADM, new ADMPay());
		}

	}

	/**
	 * 获取使用那种支付：咪咕？ MM？ 联通？ 爱游戏？ 爱动漫？
	 * 
	 * @param pPayType
	 * @return
	 */
	private SMSPay getSMSPay(String pPayType) {

		return mSMSPayMap.get(pPayType);

	}

	// ================================================
	// Activit 驱动的生命周期，如需其他生命周期可以重写下来
	// ================================================
	@Override
	public void onResume() {
		for (SMSPay mSMSPay : this.mSMSPayMap.values()) {
			mSMSPay.onResume();
		}
	}

	@Override
	public void onPause() {
		for (SMSPay mSMSPay : this.mSMSPayMap.values()) {
			mSMSPay.onPause();
		}
	}

	@Override
	public void onDestroy() {
		for (SMSPay mSMSPay : this.mSMSPayMap.values()) {
			mSMSPay.onDestroy();
		}
	}

}
